package com.young.ums.service.impl;

import com.young.common.exception.ParamException;
import com.young.common.core.dal.service.IDataAccessService;
import com.young.common.util.Page;
import com.young.common.util.StringUtils;
import com.young.interfaces.log.annotation.Log;
import com.young.ums.model.UmsConfig;
import com.young.ums.model.enums.EUmsConfigStateEnum;
import com.young.ums.cache.IUmsCacheService;
import com.young.ums.service.IUmsConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
* 统一用户配置服务实现
* Created by imrookie on 2018-9-14.
*/
@Service("umsConfigService")
public class UmsConfigServiceImpl implements IUmsConfigService {

    @Resource(name = "dataAccessService")
    IDataAccessService dataAccessService;//数据层服务

    private static final Logger logger = LoggerFactory.getLogger(UmsConfigServiceImpl.class);

    private static final String MAPPER = "com.young.ums.mapper.umsConfig";//mapper的namespace
    /**
     * 缓存服务
     */
    @Autowired
    IUmsCacheService umsCacheService;

    //获取数据列表
    @Log("查询UMS配置")
    @Override
    public List<UmsConfig> getList(UmsConfig obj) {
        return dataAccessService.getList(MAPPER + ".getList", obj);
    }

    //获取数据列表(分页)
    @Log("分页查询UMS配置")
    @Override
    public List<UmsConfig> getPage(UmsConfig obj, Page page) {
        return dataAccessService.getList(MAPPER + ".getList", obj, page);
    }

    //查询单条
    @Log("查询UMS配置")
    @Override
    public UmsConfig get(String id) {
        return dataAccessService.getObject(MAPPER + ".get", id);
    }

    //统计数量
    @Log("计数UMS配置")
    @Override
    public int count(UmsConfig obj) {
        return dataAccessService.getObject(MAPPER + ".count", obj);
    }

    //修改
    @Log("修改UMS配置")
    @Override
    public int update(UmsConfig obj) {
        obj.setUpdateTime(new Date());
        int num = dataAccessService.update(MAPPER + ".update", obj);
        if (num == 0) {
            logger.warn("[修改UMS配置] 返回更新条数为0,不再继续删除缓存,直接返回0,入参={}", obj);
            return 0;
        }
        //查询配置
        UmsConfig umsConfig = this.get(obj.getId());
        if (umsConfig != null && StringUtils.isNotBlank(umsConfig.getCkey())) {
            //删除缓存
            umsCacheService.removeUmsConfigValue(umsConfig.getCkey());
        }
        return num;
    }

    //批量删除
    @Log("批量删除UMS配置")
    @Override
    public int delete(String[] idArr) {
        int i = 0;
        for(String id : idArr){
            i += this.delete(id);
        }
        return i;
    }

    //删除单条
    @Log("删除UMS配置")
    @Override
    public int delete(String id) {
        //查询配置
        UmsConfig umsConfig = this.get(id);
        if (umsConfig == null) {
            logger.warn("[删除UMS配置] 根据id={}查询UMS配置信息为null,返回0", id);
            return 0;
        }
        //删除db
        int num = dataAccessService.delete(MAPPER + ".delete", id);
        //删除缓存
        umsCacheService.removeUmsConfigValue(umsConfig.getCkey());
        return num;
    }

    //插入
    @Log("插入UMS配置")
    @Override
    public int insert(UmsConfig obj) {
        obj.setId(obj.getCkey());
        obj.setCreateTime(new Date());
        obj.setUpdateTime(new Date());
        if (StringUtils.isBlank(obj.getState())){
            obj.setState(EUmsConfigStateEnum.DISABLE.state);//默认状态为禁用
        }
        return dataAccessService.insert(MAPPER + ".insert", obj);
    }

    //批量插入
    @Log("批量插入UMS配置")
    @Override
    public int batchInsert(List<UmsConfig> list) {
        int i = 0;
        for(UmsConfig item : list){
            i += this.insert(item);
        }
        return i;
    }

    @Log("根据key查询可用UMS配置")
    @Override
    public UmsConfig getUsableConfig(String key) {
        UmsConfig umsConfig = new UmsConfig();
        umsConfig.setState(EUmsConfigStateEnum.ENABLE.state);//可用状态
        umsConfig.setCkey(key);
        return dataAccessService.getObject(MAPPER + ".getUsableConfig", umsConfig);
    }

    @Override
    @Log("根据KEY查询有效的UMS配置值")
    public String getUsableConfigValue(String key) {
        if (StringUtils.isBlank(key)) {
            logger.error("[查询UMS配置] 入参key为空,抛出异常");
            throw new ParamException("入参key不允许为空");
        }
        //从缓存获取配置
        String val = umsCacheService.getUmsConfigValue(key);
        if (StringUtils.isNotBlank(val)) {
            logger.debug("[查询UMS配置] key={},成功命中缓存,value={}", key, val);
            return val;
        }
        UmsConfig umsConfig = new UmsConfig();
        umsConfig.setState(EUmsConfigStateEnum.ENABLE.state);//可用状态
        umsConfig.setCkey(key);
        //数据库查
        val = dataAccessService.getObject(MAPPER + ".getUsableConfigValue", umsConfig);
        logger.debug("[查询UMS配置] key={},缓存查询结果为空,查询数据库,value={}", key, val);
        if (StringUtils.isNotBlank(val)) {
            //放入缓存
            umsCacheService.setUmsConfigValue(key, val);
        }
        return val;
    }

    /**
     * 根据key查询配置值, 为空时返回默认值
     *
     * @param key        配置key
     * @param defaultVal 默认值
     * @return
     */
    @Log("查询有效的UMS配置值or默认值")
    @Override
    public String getUsableConfigValueElse(String key, String defaultVal) {
        String val = this.getUsableConfigValue(key);
        return StringUtils.isNotBlank(val) ? val : defaultVal;
    }

}